﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Abp.Runtime.Caching;
using Batman.Open.Accounts.Domains;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Open.Accounts.Readers
{
    public class WeixinMiniProgramAccountReader : ApplicationService
    {
        private const string cacheName = "WeixinMiniProgramAccountReader";

        public IRepository<OpenAccount> openAccountRepository { get; set; }

        public ICacheManager cacheManager { get; set; }

        /// <summary>
        /// 根据appId获取账号资料
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        public OpenAccount GetAccount(string appId)
        {
            // 从缓存中取数据
            var account = cacheManager.GetCache(cacheName).GetOrDefault(appId) as OpenAccount;

            if (account == null)
            {
                var query = openAccountRepository.GetAll().AsNoTracking().Where(t => t.Type == OpenAccountType.微信小程序账号);
                account = query.Where(t => t.AppId == appId).FirstOrDefault();

                if (account != null)
                {
                    // 缓存数据
                    cacheManager.GetCache(cacheName).Set(appId, account);
                }
            }

            return account;
        }
    }
}
